package com.miniserver.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;

public class FileUtils {

	/**
	 * 文件夹拷贝
	 * 
	 * @param src
	 * @param des
	 */
	public static void copy(String src, String des) {
		File file1 = new File(src);
		File[] fs = file1.listFiles();
		File file2 = new File(des);
		if (!file2.exists()) {
			file2.mkdirs();
		}
		for (File f : fs) {
			if (f.isFile()) {
				fileCopy(f.getPath(), des + "/" + f.getName()); // 调用文件拷贝的方法
			} else if (f.isDirectory()) {
				copy(f.getPath(), des + "/" + f.getName());
			}
		}
	}

	/**
	 * 文件拷贝的方法
	 */
	public static void fileCopy(String src, String des) {
		BufferedReader br = null;
		PrintStream ps = null;

		try {
			br = new BufferedReader(new InputStreamReader(new FileInputStream(
					src)));
			ps = new PrintStream(new FileOutputStream(des));
			String s = null;
			while ((s = br.readLine()) != null) {
				ps.println(s);
				ps.flush();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (br != null)
					br.close();
				if (ps != null)
					ps.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void deleteFile(File file) {
		if (file.exists()) {
			if (file.isFile()) {
				file.delete();
			} else if (file.isDirectory()) {
				File files[] = file.listFiles();
				for (int i = 0; i < files.length; i++) {
					deleteFile(files[i]);
				}
			}
			file.delete();
		}
	}
	
	/**
	 * 根据文件名检索文件夹，返回文件，支持多级目录，仅返回第一个匹配的文件
	 * @param baseDir
	 * @param filename
	 * @return
	 */
	public static File searchFile(File baseDir, final String filename) {
		File result = null;
		
		FilenameFilter filter = new FilenameFilter() {
			@Override
			public boolean accept(File dir, String name) {
				if (name.contains(".") && name.endsWith(".xml")) {
					if (name.substring(0, name.lastIndexOf(".")).equals(filename)) {
						return true;
					} else {
						return false;
					}
				} else {
					return false;
				}
			}
		};
		
		File[] files = baseDir.listFiles(filter);
		if(files != null && files.length != 0){
			result = files[0];
		} else {
			for(File file : baseDir.listFiles()){
				if(file.isDirectory()){
					result = searchFile(file, filename);
					if(result != null) {
						break;
					}
				} 
			}
		}
		
		return result;
	}

	public static void main(String[] args) {
		copy("D:\\hsqldb-2.3.1\\hsqldb\\data", "D:\\hsqldb-2.3.1\\hsqldb\\data_temp");
	}
}